<template>
  <scroller >
    <div>
      <div class="liftStatus-div" :style="liftDivStyle">
        <div class="liftStatus-body" :style="liftBodyStyle">
          <div class="liftTitle">
            <text class="floor">{{floor?floor:'1'}}</text>
          </div>

          <div class="liftStatus-inner">
            <div class="lift-middle-door">
              <div class="lift-middle-door-left" :style="leftDoor"></div>
              <div class="lift-middle-door-right" :style="rightDoor"></div>
            </div>
          </div>
          <div class="liftButton-div">
            <image v-if="direction === 'up'" src="bmlocal://assets/liftButtonUp-full.png" class="liftButton"></image>
            <image v-if="direction !== 'up'" src="bmlocal://assets/liftButtonUp-null.png" class="liftButton"></image>
            <image v-if="direction !== 'down'" src="bmlocal://assets/liftButtonDown-null.png" class="liftButton"></image>
            <image v-if="direction === 'down'" src="bmlocal://assets/liftButtonDown-full.png" class="liftButton"></image>
          </div>
        </div>
        <image v-if="liftData.smartStatus === 5" src="bmlocal://assets/liftStatus-offline.png" class="liftStatus"></image>
        <image v-if="liftData.smartStatus === 4" src="bmlocal://assets/malfunction.png" class="liftStatus"></image>
      </div>
      
      <div class="liftStatus-middle-top">
        <div class="liftStatus-middle-top-div">
          <image v-if="liftData.videoUrl2" src="bmlocal://assets/liftStatus-monitor.png" class="liftMonitor"></image>
          <image v-if="!liftData.videoUrl2" src="bmlocal://assets/liftStatus-monitor-enable.png" class="liftMonitor"></image>
          <text v-if="liftData.videoUrl2"  class="text-yellow" @click="videoShow()">打开视频监控</text>
          <text v-if="!liftData.videoUrl2" class="text-grey">打开视频监控</text>
        </div>
        <div class="liftStatus-middle-top-div" @click="listShow()">
          <image src="bmlocal://assets/liftStatus-searchDetail.png" class="liftMonitor"></image>
          <text style="color:rgb(243,149,39);">查看电梯详情</text>
        </div>
      </div>
      <div class="liftStatus-middle-bottom">
        <div class="liftStatus-row-1">
          <div class="liftStatus-colum">
            <image src="bmlocal://assets/liftStatus-status.png" style="width:50px;height:50px;"></image>
            <text style="margin-top:20px;">运行状态</text>
            <text style="margin-top:20px;color:#999999;font-size:30px;"> {{state===1?'已连接':state===2?'超时':state===3?'已断开':'未知'}}</text>
          </div>
          <div class="liftStatus-colum">
            <image src="bmlocal://assets/liftStatus-signal.png" style="width:50px;height:50px;"></image>
            <text style="margin-top:20px;">信号强度</text>
            <text style="margin-top:20px;color:#999999;font-size:30px;">{{rssi===1||rssi===2?'很弱':rssi===3||rssi===4?'弱':rssi===5||rssi===6?'正常':rssi===7||rssi===8?'强':rssi?'未知':'未知'}}</text>
          </div>
          <div class="liftStatus-colum">
            <image src="bmlocal://assets/liftStatus-floor.png" style="width:50px;height:50px;"></image>
            <text style="margin-top:20px;">楼层停靠</text>
            <text style="margin-top:20px;color:#999999;font-size:30px;">{{floor?floor+'F':'未知'}}</text>
          </div>
        </div>
        <div class="liftStatus-row-2">
          <div class="liftStatus-colum">
            <image src="bmlocal://assets/liftStatus-location.png" style="width:50px;height:50px;"></image>
            <text style="margin-top:20px;">电梯高度</text>
            <text style="margin-top:20px;color:#999999;font-size:30px;">{{currentLocation?getValueFromGroup(currentLocation,'当前位置')+'M':'0M'}}</text>
          </div>
          <div class="liftStatus-colum">
            <image src="bmlocal://assets/liftStatus-speed.png" style="width:50px;height:50px;"></image>
            <text style="margin-top:20px;">运行速度</text>
            <text style="margin-top:20px;color:#999999;font-size:30px;">{{speedNow?getValueFromGroup(speedNow,'运行速度')+'m/s':'0m/s'}}</text>
          </div>
          <div class="liftStatus-colum">
            <image src="bmlocal://assets/liftStatus-direction.png" style="width:50px;height:50px;"></image>
            <text style="margin-top:20px;">电梯方向</text>
            <text style="margin-top:20px;color:#999999;font-size:30px;">{{direction==='up'?'上升':direction==='down'?'下降':'静止'}}</text>
          </div>
        </div>
      </div>
      
      <div class="liftStatus-bottom">
        <div class="liftStatus-bottom-div">
          <text>电压:</text>
          <text style="color:#999999;margin-left:10px">{{dy?getValueFromGroup(dy,'母线电压')+'V':'0V'}}</text>
        </div>
        <div class="liftStatus-bottom-div">
          <text>电流:</text>
          <text style="color:#999999;margin-left:10px">{{dl?getValueFromGroup(dl,'输出电流')+'A':'0A'}}</text>
        </div>
      </div>

      <div class="liftStatus-bottom" @click="listAlarmAndRec()">
        <div class="liftStatus-bottom-div">
          <text>报警:</text>
          <text style="color:#999999;margin-left:10px">{{alarm}}</text>
        </div>
        <div class="liftStatus-bottom-div">
          <text>恢复:</text>
          <text style="color:#999999;margin-left:10px">{{recover}}</text>
        </div>
      </div>

    </div>
    <wxc-popup width="600"
                 :show="showLiftInfo"
                 @wxcPopupOverlayClicked="listClose"
                 pos="right">
      <scroller class="container" :style="scrollerStyle">
          <wxc-cell title="电梯工号" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.number}}</text>
            </wxc-cell>

            <wxc-cell title="内部编号" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.inNumber}}</text>
            </wxc-cell>

            <wxc-cell title="电梯型号" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.typeNumber}}</text>
            </wxc-cell>

            <wxc-cell title="维保单位" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.upkeep}}</text>
            </wxc-cell>

            <wxc-cell title="额定载重" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.loader}}</text>
            </wxc-cell>

            <wxc-cell title="额定速度" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.speed?liftData.speed+'m/s':''}}</text>
            </wxc-cell>

            <wxc-cell title="层/站/门" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.style}}</text>
            </wxc-cell>

            <wxc-cell title="智能硬件序列号" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.smartNumber}}</text>
            </wxc-cell>

            <wxc-cell title="下次年检日期" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.nextAnnual}}</text>
            </wxc-cell>

            <wxc-cell title="上次维保日期" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.lastUpkeep}}</text>
            </wxc-cell>

            <wxc-cell title="最后更新时间" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.updateTime}}</text>
            </wxc-cell>

            <wxc-cell title="使用单位" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.comName}}</text>
            </wxc-cell>

            <wxc-cell title="安装单位" :cell-style="cellStyle">
            <text :style="valueStyle">{{liftData.installer}}</text>
            </wxc-cell>  
      </scroller>
    </wxc-popup>
    <wxc-popup width="600"
                 :show="showAlarmList"
                 @wxcPopupOverlayClicked="alarmListClose"
                 pos="right">
      <scroller class="container" :style="scrollerStyle">
        <div class="list">
            <div class="policyCell"  v-for="(item,index) in alarmList" :key="index">
                <wxc-cell title="事件" :cell-style="cellStyle">
                <text :style="valueStyle">{{item.name}}</text>
                </wxc-cell>

                <wxc-cell title="事件消息" :cell-style="cellStyle">
                <text :style="valueStyle">{{item.msg}}</text>
                </wxc-cell>

                <wxc-cell title="事件状态" :cell-style="cellStyle">
                <text :style="valueStyle">{{item.status===0?'报警':'还原'}}</text>
                </wxc-cell>

                <wxc-cell title="生成时间" :has-margin="true" :has-bottom-border="false" :cell-style="cellStyle">
                <text :style="valueStyle">{{item.createTime}}</text>
                </wxc-cell>
            </div>
            <text class='text-no' v-if="alarmList.length<=0" >暂无数据</text>
        </div>
        <loading class="refresh" @loading="onloading" :display="loadinging ? 'show' : 'hide'">
            <loading-indicator class="indicator"></loading-indicator>
        </loading>
      </scroller>
      <wxc-loading :show="showLoading" :need-mask="mask"></wxc-loading>
    </wxc-popup>
    <wxc-mask v-if="!isAndroid" height="500"
              width="750"
              border-radius="0"
              duration="200"
              mask-bg-color="#FFFFFF"
              :has-animation="hasAnimation"
              :has-overlay="true"
              :show-close="true"
              :show="showVideo"
              :overlay-can-close="true"
              @wxcMaskSetHidden="videoClose()">
      <div>
        <video style="width:750;height:500" :src="liftData.videoUrl2" auto-play="true" controls></video>
      </div>
    </wxc-mask>
    <bui-dialog v-if="isAndroid" v-model="showVideo" @btnClick="videoClose" height="500" buttons="关闭" title="视频监控">
      <video style="width:600;height:500" :src="liftData.videoUrl2" auto-play="true" controls></video>
    </bui-dialog>
    
  </scroller>
</template>
<script>
var bmWebSocket = weex.requireModule('bmWebSocket')
import { WxcCell,Utils,WxcPopup,WxcMask,WxcOverlay } from 'weex-ui';
import {buiDialog} from 'bui-weex'
import { log } from 'util';
export default {
  components: {
      WxcCell,
      WxcPopup,
      Utils,
      WxcMask,
      WxcOverlay,
      buiDialog
  },
  data () {
    return {
      isAndroid:false,
      token:'',
      boxToken:'',
      pre:'',
      liftId:'',
      boxId:'',
      onopeninfo: '',
      onmessage: '',
      onerrorinfo: '',
      closeinfo: '',
      liftData:{},
      alarmList:[],
      page:1,
      pageSize:10,
      totalPages:0,
      doorState:'',
      currentLocation:'',
      floor:'',
      speedNow:'',
      direction:'',
      dy:'',
      dl:'',
      state:'',
      rssi:'',
      alarm:0,
      recover:0,
      leftDoor:{
        width:'182px'
      },
      rightDoor:{
        width:'182px'
      },
      valueStyle:{
          color:'#999999',
      },
      cellStyle:{
          height:'90px'
      },
      showLiftInfo:false,
      showVideo: false,
      showAlarmList:false,
      loadinging: false,
    }
  },
  methods: {
    connect(boxId) {
      // bmWebSocket.webSocket(`ws://zn.hyjtyl.com/smartLift/${this.pre}/websocket/${boxId}`);
      bmWebSocket.webSocket(`ws://test.hyjtyl.com/smartLift/${this.pre}/websocket/${boxId}`);
      // bmWebSocket.webSocket('ws://192.168.1.145:8080/smartLift/websocket/'+boxId);
      var self = this;
      self.onopeninfo = 'connecting...'
      bmWebSocket.onopen(function(e)
      {
        self.onopeninfo = 'websocket open';
      });
      bmWebSocket.onmessage(function(e)
      {
        var _this = self
        var name = e.data.split(',')[0]
        var value = e.data.split(',')[1]
        var doorValue = ''
        if(name.search("开门") != -1){
          doorValue = name.substring(name.indexOf('（') + 1, name.indexOf('）'))
          name = "开门"
        }
        if(name.search("关门") != -1){
          doorValue = name.substring(name.indexOf('（') + 1, name.indexOf('）'))
          name = "关门"
        }

        switch(name){
          case '母线电压':
            self.dy = value
          break;

          case '输出电流':
            self.dl = value
          break;

          case '运行速度':
            self.speedNow = value
            self.closeDoor()
          break;

          case '当前楼层':
            self.floor = value
          break;

          case '当前位置': 
            if(self.currentLocation > value){
              self.direction = 'down'
              self.currentLocation = value
              break;
            }else if(self.currentLocation < value){
              self.direction = 'up'
              self.currentLocation = value
              break;
            }
          break;

          case '关门':
            if(value == doorValue){
              self.closeDoor()
            }
          break;

          case '开门':
            if(value == doorValue){
              self.openDoor()
            }
          break;

          case 'state':
            self.state = value
          break;

          case 'rssi':
            self.rssi = value
          break;

          default: break;
        }
        
        
      });
      bmWebSocket.onerror(function(e)
      {
        self.onerrorinfo = e.data;
      });
      bmWebSocket.onclose(function(e)
      {
        self.onopeninfo = '';
        self.onerrorinfo = e.code;
      });
    },
    close:function(e) {
      bmWebSocket.close();
    },
    openDoor(){
      this.leftDoor.width = '20px'
      this.rightDoor.width = '20px'
    },
    closeDoor(){
      this.leftDoor.width = '182px'
      this.rightDoor.width = '182px'
    },
    listClose(){
      this.showLiftInfo = false
    },
    listShow(){
      this.showLiftInfo = true
    },
    videoShow(){
      this.showVideo = true
    },
    videoClose(){
      this.showVideo = false
    },
    alarmListClose(){
      this.showAlarmList = false
    },
    onloading(){
        this.loadinging = true
        if(this.totalPages == this.page){
            this.$notice.toast({
                message: '没有更多了'
            })
            setTimeout(() => {
                this.loadinging = false
            }, 500)
        }else{
            this.page = this.page + 1
            this.listAlarmAndRec()    
        } 
    },
    getLiftData(){
      let filter={liftId:this.liftId}
      this.$fetch({
          header:{
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization': `Bearer `+ this.token
          },
          method: 'POST',    
          name: 'getBox',
          data: filter
      }).then(res => {
          if(res.success){
              this.liftData = res.data
              if(res.data.smartNumber){
                this.boxId = res.data.smartNumber
                this.getBoxState(this.boxId)
                this.getCountAlarmAndRecover(this.boxId)
                this.getBoxToken()
              }
          }else{
              this.$notice.toast({
                  message: '网络错误'
              })
          }
      }, error => {
          this.$notice.toast({
              message: '网络错误'
          })
      })
    },
    getBoxState(boxId){
      let filter={boxId:boxId}
      this.$fetch({
          header:{
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization': `Bearer `+ this.token
          },
          method: 'POST',    
          name: 'findByBoxId',
          data: filter
      }).then(res => {
          if(res.success){
              this.state = res.data.state
              this.rssi = res.data.rssi
              this.connect(boxId)
          }else{
              this.$notice.toast({
                  message: '网络错误'
              })
          }
      }, error => {
          this.$notice.toast({
              message: '网络错误'
          })
      })
    },
    getCountAlarmAndRecover(boxId){
      let filter={boxId:boxId}
      this.$fetch({
          header:{
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization': `Bearer `+ this.token
          },
          method: 'POST',    
          name: 'countAlarmAndRecover',
          data: filter
      }).then(res => {
          if(res.success){
            this.alarm = res.data ? res.data.alarm : 0
            this.recover = res.data ? res.data.recover : 0
          }else{
              this.$notice.toast({
                  message: '网络错误'
              })
          }
      }, error => {
          this.$notice.toast({
              message: '网络错误'
          })
      })
    },
    listAlarmAndRec(){
      let filter = {}
      filter.boxId = this.boxId
      filter.page = this.page
      filter.pageSize = this.pageSize
      this.$fetch({
          header:{
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization': `Bearer `+ this.token
          },
          method: 'POST',    
          name: 'pageBoxAlarm',
          data: filter
      }).then(res => {
          if(res.success){
            this.alarmList = this.alarmList.concat(res.data.content)
            this.totalPages = res.data.totalPages
            this.showAlarmList = true
          }else{
              this.$notice.toast({
                  message: '网络错误'
              })
          }
      }, error => {
          this.$notice.toast({
              message: '网络错误'
          })
      })
      setTimeout(() => {
          this.loadinging = false
      }, 500)
    },
    getBoxToken(){
      this.$fetch({
          header:{
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization': `Bearer `+ this.token
          },
          method: 'POST',    
          name: 'getBoxToken',
      }).then(res => {
          if(res.success){
            this.boxToken = res.data
            this.getOrgBoxData(this.boxId)
          }else{
              this.$notice.toast({
                  message: '网络错误'
              })
          }
      }, error => {
          this.$notice.toast({
              message: '网络错误'
          })
      })
    },
    getOrgBoxData(boxId){
      let data = {}
      data.names = ["当前楼层","当前位置","运行速度"]
      data.userCache = false
      this.$fetch({
          method: 'POST',
          url: `http://cs.hyjtyl.com/api/v2/box/${boxId}/dmon/value/get`,
          header:{
            'Content-type': 'application/json',
            'Authorization': `Bearer `+ this.boxToken
          },
          data: data,
          timeout: 3000
      }).then(resData => {
          this.floor = resData[0]?resData[0].value:''
          this.currentLocation = resData[1]?resData[1].value:''
          this.speedNow = resData[2]?resData[2].value:''
      }, error => {
          this.$notice.toast({
              message: '网络错误'
          })
      })
    },
  },
  computed:{
    getValueFromGroup () {
      return (value, name) => {
        if (this.liftData.monitorGroup) {
          let res = 0
          let arr = []
          arr = this.liftData.monitorGroup[0].items.filter(item => item.name.search(name) !== -1)
          if (arr.length > 0) {
            // console.log('arr:')
            // console.log(arr)
            res = (parseFloat(value) / Math.pow(10, arr[0].fracDigits))
          } else {
            res = value
          }
          return res
        } else {
          return value
        }
      }
    }
  },
  created(){
    this.$notice.loading.show()
    this.isAndroid = Utils.env.isAndroid()
    const tabPageHeight = Utils.env.getPageHeight()
    this.liftDivStyle ={ height: tabPageHeight*0.3 + 'px' }
    this.liftBodyStyle={ height: tabPageHeight*0.3*0.9 +'px'}

    // 获取token
    this.token = this.$storage.getSync('token')
    if(!this.token){
        this.$router.setHomePage('/pages/login.js')
    } 

    this.pre = this.$storage.getSync('pre')

    this.$router.getParams().then(resData => {
      if(resData.liftId){
        this.liftId = resData.liftId
        this.getLiftData();
      }else{
        this.$notice.toast({
          message: '网络错误'
        })
      }
    })
    this.$notice.loading.hide()
    
  }
}
</script>
<style>
.liftStatus-div{
  background-color: #ffffff;
  width: 750px;
  flex-direction: row;
  justify-content: center;
  align-items: flex-end;
}
.liftStatus-body{
  background-color: #89b3fb;
  /* height: 350px; */
  width: 500px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.liftTitle{
  border:solid;
  border-width: 1px;
  border-color: #ffffff;
  background-color: #538def;
  color: #ffffff;
  width: 100;
  flex: 1;
  margin-top: 10px;
  margin-bottom: 10px;
}
.floor{
  text-align: center;
  color: #ffffff;
}
.liftStatus-inner{
  background-color: #ccdfff;
  width: 400;
  flex: 8;
  flex-direction: column;
  justify-content: center;
  align-items:center;
  
}
.lift-middle-door{
  background-color: #92AEDF;
  width: 370;
  flex: 1;
  margin-top: 15;
  flex-direction: row;
  justify-content: space-between;
}
.lift-middle-door-left{
  /* flex: 10; */
  /* width: 180px; */
  background-color: #eef4ff;
  transition-property: width;
  transition-duration: 1s;
}
.lift-middle-door-right{
  /* flex: 10; */
  /* width: 180px; */
  background-color: #eef4ff;
  transition-property: width;
  transition-duration: 1s;
}
.liftButton-div{
  position: absolute;
  width: 50px;
  height: 70px;
  right: 0px;
  top: 150px;
  justify-content: center;
  align-items: center;
}
.liftButton{
  width: 30px;
  height: 30px; 
}
.liftStatus{
  width: 50px;
  height: 50px;
  position:absolute;
  right: 35;
  top: 150;
}
.liftStatus-middle-top{
  flex-direction: row;
  height: 70px;
}
.liftStatus-middle-top-div{
  flex: 1;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.liftMonitor{
  width: 50px;
  height: 50px;; 
}
.liftStatus-middle-bottom{
  height: 500px;
  background-color: #ffffff;
  flex-direction: column;
}
.liftStatus-row-1{
  flex: 1;
  border-bottom: solid;
  border-bottom-width: 1px;
  border-color: #999999;
  flex-direction: row;
}
.liftStatus-row-2{
  flex: 1;
  flex-direction: row;
}
.liftStatus-colum{
  flex: 1;
  border-right: solid;
  border-right-width: 1px;
  border-color: #999999;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.liftStatus-bottom{
  flex-direction: row;
  justify-content: space-around;
  background-color: #ffffff;
  height: 100px;
  margin-top: 20px;
}
.liftStatus-bottom-div{
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}
.text-no{
  text-align: center;
  margin-top: 100;
  font-size: 35;
  color: #999999
}
.container {
    background-color: #f2f3f4;
}
.text-yellow{
  color: rgb(243,149,39)
}
.text-grey{
  color: rgb(160,157,157)
}
.refresh {
    width: 750px;
    height: 100px;
    display: -ms-flex;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}
.indicator {
    /* margin-top: 16px; */
    height: 80px;
    width: 80px;
    color: #f49428;
}
</style>
